package com.wkk.websocket.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkk.authentication.entity.UmsUser;
import com.wkk.utils.NoBugTools;
import com.wkk.websocket.config.WebSocketHandle;
import com.wkk.websocket.constant.WebSocketConstant;
import com.wkk.websocket.dto.AnnouncementHistoryDto;
import com.wkk.websocket.dto.MessageChatDto;
import com.wkk.websocket.entity.Announcement;
import com.wkk.websocket.mapper.AnnouncementMapper;
import com.wkk.websocket.service.AnnouncementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author : WangKeKe
 * @date : 2020/9/30 15:01
 * Description :
 */


@Service
@Slf4j
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnouncementService {

    @Autowired
    private WebSocketHandle webSocketHandle;

    @Override
    public boolean releaseAnnouncement(String content) {
        // 由于此类接口需要通过token认证
        // 所以可以从Subject中获取用户消息,不需要通过前端传递,
        // 也不需要传递数据库 - 在token认证的时候其实已经查过一次数据库或者缓存了，并将用户信息放在了subject中
        Subject subject = SecurityUtils.getSubject();
        UmsUser umsUser = (UmsUser) subject.getPrincipal();
        Announcement announcement = new Announcement()
                .setType(WebSocketConstant.CMD_USER)
                .setCreateBy(umsUser.getId())
                .setContent(content);
        // 发送公告
        String msg = "成功";
        MessageChatDto messageChatDto = new MessageChatDto()
                .setHeadUrl(umsUser.getHeadUrl())
                .setNickname(umsUser.getNickname())
                .setSendUserId(umsUser.getId())
                .setMsgContent(content)
                .setMsgType(WebSocketConstant.MSG_TYPE_ANNOUNCEMENT);
        try {
            webSocketHandle.sendAllMessage(JSONObject.toJSONString(messageChatDto));
        } catch (Exception e) {
            announcement.setStatus(WebSocketConstant.MSG_STATUS_ERROR)
                    .setFailCause(e.getMessage());
            msg = "失败";
        }
        // 消息持久化
        baseMapper.insert(announcement);
        log.info("公告发布" + msg + ">>>>>公告ID：" + announcement.getId());
        return NoBugTools.isNotEmpty(announcement.getId());
    }

    @Override
    public Page<AnnouncementHistoryDto> queryPage(Integer pageNo, Integer pageSize) {
        Page<AnnouncementHistoryDto> page = new Page<>(pageNo, pageSize);
        page.setRecords(baseMapper.queryPageList(page));
        return page;
    }
}
